//服务器入口文件
const express = require('express');
//post引入依赖bodyparse
const bodyParse = require('body-parser');
//读取文件依赖
const {
  readFileSync
} = require('fs');
//绝对路径依赖
const {
  resolve
} = require('path');

const myResult = [];

const app = express();


//中间件
//开启post请求功能
app.use(bodyParse.urlencoded({
  extended: true
}));
app.use(bodyParse.json());

//跨域设置
app.all('*', function (req, res, next) {
  //请求头允许所有的源
  res.header('Access-Control-Allow-Origin', '*');
  //请求头允许的请求方式
  res.header('Access-Control-Allow-methods', 'GET', 'POST');
  next();
});

//API接口
/**
 * 响应题目信息
 * 接收请求数据:
 * @order 题目序号
 */
app.post('/getQuestion', function (req, res) {
  //缓存前端请求的数据
  const order = req.body.order;
  //读取服务器的数据
  const questionData = JSON.parse(readFileSync(resolve(__dirname, 'data/question.json'), 'utf8'));
  //匹配前端/后端数据 得到题目信息数据
  const questionResult = questionData[order];

  /**
   * 排除answer字段的数据
   *   {
         "id": 1,
         "question": "1 + 1 = ?",
         "items": ["2", "5", "4", "3"],
         "answer": 0
       }
   */
  if (questionResult) {
    const {
      id,
      question,
      items
    } = questionResult;

    //响应数据给前端
    res.send({
      errorCode: 0,
      msg: 'ok',
      data: {
        id,
        question,
        items
      }
    });
  } else {
    res.send({
      errorCode: 1,
      msg: 'NO_DATA',
      data: myResult
    });
    myResult = [];
  }
});

/**
 * 提交上传答案
 * 接收请求参数:
 * @order 题目序号
 * @myAnswer 用户填写提交的答案下标
 */
app.post('/uploadAnswer', function (req, res) {
  const {
    order,
    myAnswer
  } = req.body;

  //读取服务器的数据
  const questionData = JSON.parse(readFileSync(resolve(__dirname, 'data/question.json'), 'utf8'));

  //解构服务器的数据对应当前项的数据questionData[0]/questionData[order][1]
  const {
    id,
    question,
    items,
    answer
  } = questionData[order];

  //服务器缓存的结果数据：
  myResult.push({
    qid: id,
    question,
    //items[myAnswer] => items[2]
    myAnswer: items[myAnswer],
    //items[answer] => items[0]
    rightAnswer: items[answer],
    //用户填写的答案下标与服务器存的答案一致就返回true
    isRight: myAnswer == answer
  });

  //响应数据
  res.send(myResult);
  /**
   * [
   *   {
          "qid": 2,
          "question": "1 + 2 = ?",
          "myAnswer": "3",
          "rightAnswer": "3",
          "isRight": true
        }
      ]
   */
});

app.listen(8888, function () {
  console.log('welcome to use Express on 8888');
})